#include "MAX7219.h"
#include <string.h>

void MAX7219::write_byte(uint8_t byte)
{
    CS.write(0);
    for (int i = 0; i < 8; i++)
    {
        CLK.write(0);

        if (byte & 0x80)
            DIN.write(1);
        else
            DIN.write(0);
        byte <<= 1;

        CLK.write(1);
        
    }
}

void MAX7219::write_data(uint8_t addr, uint8_t data)
{
    CS.write(0);
    write_byte(addr);
    write_byte(data);
    CS.write(1);
}

void MAX7219::write(uint8_t com, uint8_t show_data)
{
    write_data(8 - com, show_data);
    // write_data(8-(com+1),write_data);
}

void MAX7219::write(int number)
{
    int fu = 0;
    if (number < 0)
        fu = 1;
    number = number > 99999999 ? 99999999 : number;
    number = number < -9999999 ? -9999999 : number;
    uint8_t data[8];
    memset((void *)data, MAX7219_BIT_DIS, 8);
    int num = number;
    num = num < 0 ? -num : num;
    for (int i = 0; i < 8; i++)
    {
        if (num == 0)
        {
            if (fu == 1)
            {
                data[7 - i] = MAX7219_BIT_FU;
            }
            break;
        }
        data[7 - i] = num % 10;
        num /= 10;
    }

    for (int i = 0; i < 8; i++)
    {
        write_data(8 - i, data[i]);
    }
}
